package com.example.demo001.interceptor;

import com.example.demo001.constant.JwtClaimsConstant;
import com.example.demo001.constant.MessageConstant;
import com.example.demo001.constant.StatusCode;
import com.example.demo001.context.BaseContext;
import com.example.demo001.exception.BaseException;
import com.example.demo001.properties.JwtProperties;
import com.example.demo001.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    private final JwtProperties jwtProperties;
    private final RedisTemplate<String, String> redisTemplate;

    // 使用构造函数注入
    public UserInterceptor(JwtProperties jwtProperties, RedisTemplate<String, String> redisTemplate) {
        this.jwtProperties = jwtProperties;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 校验jwt
     *
     */
    @Override
    public boolean preHandle(@Nullable HttpServletRequest request,@Nullable HttpServletResponse response,@Nullable Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        if (request == null) {
            throw new AssertionError();
        }
        String token = request.getHeader(jwtProperties.getToken());
        if(StringUtils.isBlank(token)){
            throw new BaseException(StatusCode.TOKEN_ERROR, MessageConstant.TOKEN_IS_NULL);
        }

        //2、校验令牌
        Claims claims = null;
        log.info("token校验:{}", token);
        try {
            claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
        } catch (Exception ex) {
            throw new BaseException(StatusCode.TOKEN_ERROR, MessageConstant.TOKEN_ERROR);
        }
        String username = claims.get(JwtClaimsConstant.USERNAME).toString();
        String redisToken = redisTemplate.opsForValue().get(JwtClaimsConstant.TOKEN + username);
        if( StringUtils.isBlank(redisToken)){
            throw new BaseException(StatusCode.TOKEN_ERROR, MessageConstant.TOKEN_CHECK_FAILED);
        }
        if(!redisToken.equals(token)){
            throw new BaseException(StatusCode.USER_IS_LOGIN, MessageConstant.USER_IS_LOGIN);
        }

        //刷新redis中的token过期时间
        redisTemplate.expire(JwtClaimsConstant.TOKEN + username, jwtProperties.getTtl(), TimeUnit.MILLISECONDS);

        //存入到ThreadLocal中
        BaseContext.setCurrentId(username);
        return true;
    }


    @Override
    public void postHandle(@Nullable HttpServletRequest request,@Nullable HttpServletResponse response,@Nullable Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        BaseContext.removeCurrent();
    }

}

